<?php

namespace app\qsapi\model;

use think\Db;

class BoxLoginFirstLog extends BaseModel
{
    protected $connection = 'Db_log';
    protected $table = 'cq_box_login_first_log';

    public function createFirstLoginLog($data): array
    {
        // write_log('info','model/BoxLoginFirstLog.php',"kafaka消费数据过来了:".json_encode($data),'kafka_insert_box_login_first_log',true);
        try {
            $member_id = $data['member_id'];
            $result    = $this->where('member_id', '=', $member_id)->find();
            if ($result) {
                throw new \Exception('用户已存在');
            }
            $data['network']  = isset($data['network']) ? json_decode('"' . $data['network'] . '"') : '';
            $data['net_isp']  = isset($data['net_isp']) ? json_decode('"' . $data['net_isp'] . '"') : '';
            $ip               = isset($data['login_ip']) ? json_decode('"' . $data['login_ip'] . '"') : '';
            $ip_info          = ip2city($ip);
            $data['province'] = $ip_info['province'] ?? '';
            $data['city']     = $ip_info['city'] ?? '';
            $data['area']     = $ip_info['area'] ?? '';

            //如果为小号, 获取主账号ID
            if($data['type'] == 2){
                $data['member_pid'] = Member::where('id','=',$member_id)->value('pid') ?? 0;
            }

            $id = $this->insert($data);
            if (!$id) throw new \Exception('上报失败');
            return ['code' => 0, 'msg' => '上报成功'];
        } catch (\Exception $e) {
            // write_log('info','model/BoxLoginFirstLog.php',"kafaka首登日志消费写入报错:".json_encode($e->getMessage()),'kafka_insert_box_login_first_log',true);
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}